file_path_gro = 'md_0_1.gro'
file_path_xpm = 'hbmap.xpm'
file_path_ndx = 'hbond.ndx'

ndx_list = []
with open(file_path_ndx, 'r') as file:
    for i in file:
        ndx_list.append(i.strip())
#print(ndx_list[-1])

##拆分 ndx 文件
split_element = '[ hbonds_Protein-NAP_TUD ]'
ndx_list_1 = []
ndx_list_2 = []
# 遍历列表元素
for element in ndx_list:
    if element == split_element:
        break  # 遇到拆分标识，停止遍历
    ndx_list_1.append(element)

# 继续遍历列表元素，添加到第二个列表
for element in ndx_list[len(ndx_list_1) + 1:]:
    ndx_list_2.append(element)
# 打印拆分后的两个列表

#print(ndx_list_2)
ndx_list_index1_index2 = [[],[]]
for i in ndx_list_2:
    ndx_list_index1_index2[0].append(i.split("     -1   ")[0])
    ndx_list_index1_index2[1].append(i.split("     -1   ")[1])
#print(ndx_list_index1_index2)


gro_list_name_index = [[],[]]
with open(file_path_gro, 'r') as file:
    for i in file:
        gro_list_name_index[0].append(i.strip()[0:13])
        gro_list_name_index[1].append(i.strip()[13:20].strip())
#print(gro_list_name_index)
#print(ndx_list_index1_index2[0])
#print(ndx_list_index1_index2[1])
#print(gro_list_name_index[1])
for i in range(len(ndx_list_index1_index2[0])):
    for j in range(len(gro_list_name_index[0])):
        if ndx_list_index1_index2[0][i].strip() ==  gro_list_name_index[1][j].strip():
            ndx_list_index1_index2[0][i] = gro_list_name_index[0][j]
    for k in range(len(gro_list_name_index[0])):
        if ndx_list_index1_index2[1][i].strip() ==  gro_list_name_index[1][k].strip():
            ndx_list_index1_index2[1][i] = gro_list_name_index[0][k]
#print(ndx_list_index1_index2[0])
#print(ndx_list_index1_index2[1])

ndx_list_index_all = []
for i in range(len(ndx_list_index1_index2[0])):
    ndx_list_index_all.append(ndx_list_index1_index2[0][i] + "," + ndx_list_index1_index2[1][i])
#print(ndx_list_index_all)
#
#print(len(ndx_list_index_all))

hb_xpm = []
with open(file_path_xpm, 'r') as file:
    for i in file:
        hb_xpm.append(i.strip())

hb_xpm_hb_num = []
hb_xpm_hb_num2 = []
for i in range(len(ndx_list_index_all)):
    hb_xpm_hb_num.append(hb_xpm[139+i].strip())

for i in range(len(hb_xpm_hb_num)):
    hb_xpm_hb_num2.append(hb_xpm_hb_num[i].count("o"))

#print(len(hb_xpm_hb_num2))

for i in range(len(ndx_list_index_all)):
    ndx_list_index_all[i] = ndx_list_index_all[i] + "," + str(hb_xpm_hb_num2[i]) + "," + str(hb_xpm_hb_num2[i]/100) + "\n"
#print(ndx_list_index_all)

ndx_list_index_all.insert(0,"氢键供体,氢键受体,氢键数量,占有率(%) \n")

csv = open("hb-csv.csv","w+")
csv.writelines(ndx_list_index_all)
csv.close()